package com.gao.modules.user.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gao.base.Result;
import com.gao.modules.depart.pojo.SysDepart;
import com.gao.modules.depart.service.SysDepartService;
import com.gao.modules.depart.vo.SysDepartLoginVo;
import com.gao.modules.role.pojo.SysRole;
import com.gao.modules.role.service.SysRoleService;
import com.gao.modules.role.vo.SysRoleLoginVo;
import com.gao.modules.user.pojo.SysUser;
import com.gao.modules.user.mapper.SysUserMapper;
import com.gao.modules.user.service.SysUserService;
import com.gao.modules.user.vo.SysUserVo;
import com.gao.modules.userdepart.pojo.SysUserDepart;
import com.gao.modules.userdepart.service.SysUserDepartService;
import com.gao.modules.userrole.pojo.SysUserRole;
import com.gao.modules.userrole.service.SysUserRoleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Resource
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserDepartService sysUserDepartService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private SysDepartService sysDepartService;

    @Autowired
    private SysRoleService sysRoleService;

    @Override
    @Transactional
    public Result insert(SysUser sysUser, SysUserDepart sysUserDepart, SysUserRole sysUserRole) {
        Integer existNum = sysUserMapper.existNumByUserName(sysUser.getUserName());
        if ((existNum != null) && (existNum != 1)) {
            return Result.error("该工号已经存在，请检查后重新输入");
        } else if (existNum > 1) {
            return Result.error("该工号已经多个，请联系管理员查重");
        } else {
            this.save(sysUser);
            sysUserDepartService.save(sysUserDepart);
            sysUserRoleService.save(sysUserRole);
        }
        return Result.success();
    }

    @Override
    @Transactional
    public Result deleteUserById(String userId) {
        try {
            this.removeById(userId);
            sysUserRoleService.remove(new QueryWrapper<SysUserRole>()
                    .eq("user_id", userId));
            sysUserDepartService.remove(new QueryWrapper<SysUserDepart>()
                    .eq("user_id", userId));
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("删除错误，请检查该ID是否存在或请再次尝试");
        }

    }

    @Override
    @Transactional
    public Result updateUserById(SysUser sysUser, SysUserDepart sysUserDepart, SysUserRole sysUserRole) {
        boolean userUpdateFlag = this.update(new QueryWrapper<SysUser>().eq("id", sysUser.getId()));
        boolean userDepartRemoveFlag = sysUserDepartService.remove(new QueryWrapper<SysUserDepart>().eq("user_id", sysUser.getId()));
        boolean userDepartSaveFlag = sysUserDepartService.save(sysUserDepart);
        boolean userRoleRemoveFlag = sysUserRoleService.remove(new QueryWrapper<SysUserRole>().eq("user_id", sysUser.getId()));
        boolean userRoleSaveFlag = sysUserRoleService.save(sysUserRole);
        if (userUpdateFlag
                && userDepartRemoveFlag
                && userDepartSaveFlag
                && userRoleRemoveFlag
                && userRoleSaveFlag) {
            return Result.success();
        } else {
            return Result.error("更新失败，请重新尝试");
        }
    }

    @Override
    public IPage<SysUserVo> queryDepartAllUser(String departName, Page page) {
        return sysUserMapper.queryDepartAllUser(page, departName);
    }

    @Override
    public SysUserVo getUserDetailForLogin(SysUser user) {
        SysUserVo sysUserVo = new SysUserVo();
        BeanUtils.copyProperties(user, sysUserVo);
        sysUserVo.setUserId(user.getId());
        //查询出所有的部门
        List<SysDepartLoginVo> departLoginVoList = new ArrayList<>();
        List<SysUserDepart> sysUserDeparts = sysUserDepartService.list(new QueryWrapper<SysUserDepart>().eq("user_id", user.getId()));
        sysUserDeparts.forEach(r -> {
            SysDepart sysDepart = sysDepartService.getById(r.getDepartId());
            SysDepartLoginVo sysDepartLoginVo = new SysDepartLoginVo(sysDepart);
            departLoginVoList.add(sysDepartLoginVo);
        });
        sysUserVo.setDepartLoginVos(departLoginVoList);
        //角色
        List<SysRoleLoginVo> sysRoleLoginVos = new ArrayList<>();
        List<SysUserRole> sysUserRoleList = sysUserRoleService.list(new QueryWrapper<SysUserRole>().eq("user_id", user.getId()));
        sysUserRoleList.forEach(r -> {
            SysRole sysRole = sysRoleService.getById(r.getRoleId());
            SysRoleLoginVo sysRoleLoginVo = new SysRoleLoginVo(sysRole);
            sysRoleLoginVos.add(sysRoleLoginVo);
        });
        sysUserVo.setRoleLoginVos(sysRoleLoginVos);
        return sysUserVo;
    }


}
